package com.cloud.adrian.novel.common.auth;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.util.Objects;

/**
 * Jwt 工具类
 * @Author: xiangguiliang
 * @since: 2024/05/03
 */
@Slf4j
@UtilityClass
public class JwtUtils {
    /**
     * Jwt加密密钥
     */
    private static final String SECRET = "E66559580A1ADF48CDD928516062F12E";

    /**
     * 定义系统标识头常量
     */
    private static final String HEADER_SYSTEM_KEY = "systemKeyHeader";

    /**
     * 根据用户id生成Jwt
     * @param uid       用户id
     * @param systemKey 系统标识
     * @return Jwt
     */
    public String generateToken(Long uid, String systemKey) {
        return Jwts.builder()
                .setHeaderParam(HEADER_SYSTEM_KEY, systemKey)
                .setSubject(uid.toString())
                .signWith(Keys.hmacShaKeyFor(SECRET.getBytes(StandardCharsets.UTF_8)))
                .compact();
    }

    /**
     * 解析Jwt返回用户id
     * @param token     Jwt
     * @param systemKey 系统标识
     * @return 用户id
     */
    public Long parseToken(String token, String systemKey) {
        try {
            Jws<Claims> claimsJws;
            claimsJws = Jwts.parserBuilder()
                    .setSigningKey(Keys.hmacShaKeyFor(SECRET.getBytes(StandardCharsets.UTF_8)))
                    .build()
                    .parseClaimsJws(token);
            if (Objects.equals(claimsJws.getHeader().get(HEADER_SYSTEM_KEY), systemKey)) {
                return Long.parseLong(claimsJws.getBody().getSubject());
            }
        } catch (JwtException e) {
            log.warn("Jwt解析异常: {}", token);
        }
        return null;
    }
}
